using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Principal;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

using SqlWebAdmin.CSharp;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
		Response.Redirect("~/home.aspx"); // toss them to home.
        if (!IsPostBack)
        {
            lblError.Visible = false;
            lblLogoutInfo.Visible = false;
            lblLoginInfo.Visible = true;

            txtServer.Text = "(local)";
            Session["serverName"] = txtServer.Text;

            if (ddlAuthType.SelectedIndex == 0)
            {
                txtUsername.Text = WindowsIdentity.GetCurrent().Name;
            }
            else
            {
                txtUsername.Text = "sa";
            }
        }

        if (Request.QueryString["error"] != null)
        {
            switch (Request.QueryString["error"])
            {
                case "sessionexpired":
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">Your session has expired. Please enter your login information again.</div>";
                    break;
                case "userinfo":
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">Invalid username and/or password, or server does not exist.<br>Also, please ensure that SQL Server Authentication is enabled on the server.</div>";
                    break;
                default:
                    lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">An unknown error has occured.</div>";
                    break;
            }
        }
        else
        {
            if (Request.QueryString["action"] == "logout")
            {
                lblLogoutInfo.Visible = true;
                lblLoginInfo.Visible = false;
            }
        }
    }


    protected void ddlAuthType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlAuthType.SelectedIndex == 0)
        {
            txtUsername.Text = WindowsIdentity.GetCurrent().Name;
            txtUsername.Enabled = false;
            txtPassword.Enabled = false;
        }
        else
        {
            txtUsername.Enabled = true;
            txtPassword.Enabled = true;
            txtUsername.Text = "sa";
        }
    }
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        if (IsValid)
        {
            string serverName = txtServer.Text.Trim();
            string userName = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            Server smoServer = new Server(serverName);
            try
            {
                if (ddlAuthType.SelectedIndex == 1)
                {
                    smoServer.ConnectionContext.LoginSecure = false;
                    smoServer.ConnectionContext.Login = userName;
                    smoServer.ConnectionContext.Password = password;
                }

                ServerVersion serverVersion = smoServer.ConnectionContext.ServerVersion;


				Profile.ServerName = serverName;
				
                Session["serverName"] = serverName;
                Session["useIntegratedSecurity"] = smoServer.ConnectionContext.LoginSecure;
                Session["username"] = userName;
                Session["password"] = Encryption.Current().Encrypt(password);

				FormsAuthentication.SetAuthCookie(userName, false);

				// take a look and see if there is any redirect url for us.  if not redirect to home.
				string redirUrl = FormsAuthentication.GetRedirectUrl(userName, false);
				if (redirUrl.ToLower() == Request.ServerVariables["SCRIPT_NAME"].ToLower())
				{
					
					redirUrl = "~/home.aspx";
				}
			
				// get the connection string, we can use this to rehydrate the connection to SMO
				string connString = smoServer.ConnectionContext.ConnectionString;
				Encryption crypt = Encryption.Current();
				// encrypt the connection string
				string cryptedConnString = crypt.Encrypt(connString);

				// store it in profile
				Profile.ConnectionString = cryptedConnString;

				Response.Redirect(redirUrl);

            }
            catch (Microsoft.SqlServer.Management.Smo.SmoException smoEx)
            {
                lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">" + HttpUtility.HtmlEncode(Common.ConcatenateExceptions(smoEx)) + "</div>";
                lblError.Visible = true;
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text = "<div class=\"error\" style=\"padding-top:35px;padding-bottom:35px;\">" + HttpUtility.HtmlEncode(Common.ConcatenateExceptions(ex)) + "</div>";
            }

            
        }

    }
}
